<template>
  <div class="org">
    <div class="page-head">
      <div class="page-title">机构管理</div>
      <div class="page-tool">
        <el-select
          v-model="licenseState"
          placeholder="license状态"
          class="tool-sel"
          clearable
        >
          <el-option
            v-for="item in licenses"
            :key="item.key"
            :value="item.key"
            :label="item.value"
          ></el-option>
        </el-select>
        <search-input placeholder="机构名称" @search="searchChange" />
        <div
          class="tool-btn"
          @click="open('add')"
          v-if="$permiss(btnPermiss, '新增机构')"
        >
          新增机构
        </div>
      </div>
    </div>
    <div class="page-body">
      <div class="table_data">
        <el-scrollbar class="scroll-bar">
          <el-table :data="tableData" stripe :fit="true">
            <el-table-column width="20" />
            <el-table-column
              prop="name"
              :show-overflow-tooltip="true"
              label="机构名称"
            >
            </el-table-column>

            <el-table-column
              prop="organization"
              width="80"
              label="机构类型"
              :show-overflow-tooltip="true"
            >
              <template slot-scope="{ row }">               
                <div>
                  {{
                    organizations.find((o) => o.key == row.organization).value
                  }}
                </div>
              </template>
            </el-table-column>

            <el-table-column
              width="80"
              :show-overflow-tooltip="true"
              prop="type"
              label="党建模式"
            >
              <template slot-scope="{ row }">            
                <div>
                  {{ customerTypes.find((c) => c.key === row.type).value }}
                </div>
              </template>
            </el-table-column>
            <el-table-column :show-overflow-tooltip="true" label="客户区域">
              <template slot-scope="{ row }">
                <div>
                  {{ row.province_name }}{{ row.city_name
                  }}{{ row.district_name }}
                </div>
              </template>
            </el-table-column>
            <el-table-column
              :show-overflow-tooltip="true"
              prop="create_time"
              label="创建时间"
              width="150"
            >
            </el-table-column>
            <el-table-column
              :show-overflow-tooltip="true"
              prop="license"
              label="license状态"
              width="120"
              align="center"
            >
              <template slot-scope="{ row }">
                <div
                  class="licenseButton"
                  :class="licenses.find((l) => l.key === row.license).className"
                >
                  {{ licenses.find((l) => l.key === row.license).value }}
                </div>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="360">
              <template slot-scope="{ row }">
                <div class="operation-col">
                  <div v-if="$permiss(btnPermiss, 'License')" class="txt-btn ope-btn primary" @click="jump('license', row)">
                    License
                  </div>
                  <div v-if="$permiss(btnPermiss, '联系人')" class="txt-btn ope-btn primary" @click="jump('contact', row)">
                    联系人
                  </div>
                  <div v-if="$permiss(btnPermiss, '账号')" class="txt-btn ope-btn primary" @click="jump('customer', row)">
                    账号
                  </div>
                  <div
                    v-if="$permiss(btnPermiss, '修改')"
                    class="txt-btn ope-btn primary"
                    @click="open('edit', row)"
                  >
                    修改
                  </div>
                  <div v-if="$permiss(btnPermiss, '切换模式')" class="txt-btn ope-btn primary" @click="changeType(row)">
                    切换模式
                  </div>
                  <div v-if="$permiss(btnPermiss, '详情')" class="txt-btn primary" @click="openDetail(row)">
                    详情
                  </div>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-scrollbar>
      </div>
      <div class="page-footer">
        <pagina-tion
          class="page-pager"
          v-show="total >= 0"
          :background="true"
          :total="total"
          :offset.sync="offset"
          :limit.sync="limit"
          @pagination="getChangePage"
        />
        <button class="page-button">确定</button>
      </div>
    </div>
    <!-- 新增和修改弹框 -->
    <el-dialog
      :visible.sync="model.visible"
      width="675px"
      :title="model.type === 'add' ? '新增机构' : '修改机构'"
      :close-on-click-modal="false"
      :show-close="false"
    >
      <div class="dialog-body detail-body">
        <el-form
          ref="form"
          :model="form"
          label-width="110px"
          label-position="left"
        >
          <el-form-item label="机构名称" class="required">
            <el-input
              name="companyName"
              v-model="form.name"
              v-validate="'required|companyName'"
            />
            <div v-show="errors.has('companyName')" class="el-form-item__error">
              {{ errors.first("companyName") }}
            </div>
          </el-form-item>
          <el-form-item label="上级机构" class="required">
            <el-radio-group v-model="form.top">
              <el-radio
                v-for="item in haveOrNot"
                :label="item.key"
                :key="item.key"
                >{{ item.value }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
          <el-form-item
            v-if="form.top === 1"
            class="under-item required secSty"
          >
            <el-select
              v-model="form.parent_id"
              placeholder="请选择上级机构"
              name="parent_id"
              v-validate="'required'"
              class="selectInp"
            >
              <el-option
                v-for="item in organizationData"
                :key="item.org_id"
                :label="item.name"
                :value="item.org_id"
              >
                <el-tooltip effect="dark" placement="right">
                  <div slot="content">
                    {{ item.name }}
                  </div>
                  <div>
                    {{ item.name }}
                  </div>
                </el-tooltip>
                   
              </el-option>
            </el-select>
            <div v-show="errors.has('parent_id')" class="el-form-item__error">
              {{ errors.first("parent_id") }}
            </div>
          </el-form-item>
          <el-form-item
            label="客户地址"
            prop="roles"
            label-position="left"
            class="required"
          >
            <el-select
              v-model="form.province"
              name="province"
              placeholder="省"
              class="area-sel"
              @change="areaChange($event, 'city')"
              v-validate="'required'"
            >
              <el-option
                v-for="item in provinceList"
                :key="item.code"
                :label="item.name"
                :value="item.code"
              />
            </el-select>
            <div
              v-show="errors.has('province')"
              class="el-form-item__error zone"
            >
              {{ errors.first("province") }}
            </div>
            <el-select
              v-model="form.city"
              name="city"
              placeholder="市"
              class="area-sel"
              @change="areaChange($event, 'district')"
              v-validate="'required'"
            >
              <el-option
                v-for="item in cityList"
                :key="item.code"
                :label="item.name"
                :value="item.code"
              />
            </el-select>
            <div
              v-show="errors.has('city')"
              class="el-form-item__error zone city"
            >
              {{ errors.first("city") }}
            </div>
            <el-select
              v-model="form.district"
              name="district"
              placeholder="区"
              class="area-sel"
              v-validate="'required'"
            >
              <el-option
                v-for="item in districtList"
                :key="item.code"
                :label="item.name"
                :value="item.code"
              />
            </el-select>
            <div
              v-show="errors.has('district')"
              class="el-form-item__error zone district"
            >
              {{ errors.first("district") }}
            </div>
          </el-form-item>
          <el-form-item class="under-item required">
            <el-input
              v-model="form.location"
              placeholder="请输入详细地址"
              name="location"
              v-validate="'required|location'"
            >
            </el-input>
            <div v-show="errors.has('location')" class="el-form-item__error">
              {{ errors.first("location") }}
            </div>
          </el-form-item>
          <el-form-item label="机构类型" label-position="left" class="required">
            <el-select
              v-model="form.organization"
              name="organization"
              placeholder="请选择机构类型"
              v-validate="'required'"
            >
              <el-option
                v-for="item in organizations"
                :key="item.key"
                :label="item.value"
                :value="item.key"
              />
            </el-select>
            <div
              v-show="errors.has('organization')"
              class="el-form-item__error"
            >
              {{ errors.first("organization") }}
            </div>
          </el-form-item>
          <el-form-item
            v-if="model.type == 'add'"
            label="党建模式"
            class="required"
          >
            <el-radio-group v-model="form.type">
              <el-radio
                v-for="item in customerTypes"
                :label="item.key"
                :key="item.key"
                >{{ item.value }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
          <el-form-item v-if="isShowModel" class="under-item required">
            <el-input
              :disabled="true"
              v-model="form.serial"
              name="serial"
              v-validate="'required|serial'"
              placeholder="请输入主控序列号"
            ></el-input>
            <div v-show="errors.has('serial')" class="el-form-item__error">
              {{ errors.first("serial") }}
            </div>
          </el-form-item>
          <el-form-item label="是否合同主体" class="required">
            <el-radio-group v-model="form.contract" @change="radioChange">
              <el-radio
                v-for="item in haveOrNot"
                :label="item.key"
                :key="item.key"
                >{{ item.value }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
          <el-form-item v-if="form.contract === 1" class="under-item required">
            <el-input
              placeholder="请输入合同编号"
              v-model="form.contract_number"
              name="contract_number"
              :maxlength="32"
              v-validate="'required|noChinese'"
            ></el-input>
            <div
              v-show="errors.has('contract_number')"
              class="el-form-item__error zone"
            >
              {{ errors.first("contract_number") }}
            </div>
          </el-form-item>
          <el-form-item v-if="form.contract === 1" class="under-item required">
            <el-date-picker
              v-model="form.contract_time"
              type="date"
              placeholder="选择合同签订时间"
              name="contract_time"
              :picker-options="pickerOptions"
              v-validate="'required'"
            >
            </el-date-picker>
            <div
              v-show="errors.has('contract_time')"
              class="el-form-item__error"
            >
              {{ errors.first("contract_time") }}
            </div>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="close">取 消</el-button>
        <el-button type="primary" @click="submit">保 存</el-button>
      </span>
    </el-dialog>
    <!--详情弹框 -->
    <el-dialog
      :visible.sync="detailVisable"
      v-if="detailVisable"
      width="635px"
      title="机构详情"
      :close-on-click-modal="false"
      :show-close="true"
      @close="closeDetail"
    >
      <div class="dialog-body detail-body" id="detail">
        <el-form label-width="110px" label-position="left">
          <el-form-item label="机构名称：" class="mb10">
            <div class="color333">{{ detail.name }}</div>
          </el-form-item>
          <el-form-item label="上级机构：" class="mb10">
            <div v-if="detail.top === 1" key="yes" class="color333">
              {{
                organizationData.find((o) => o.org_id === detail.parent_id).name
              }}
            </div>
            <div v-else key="no">无</div>
          </el-form-item>
          <el-form-item
            label="客户地址："
            label-position="left"
            class="mb10"
          >
            <div class="color333">
              {{ detail.province_name }}{{ detail.city_name
              }}{{ detail.district_name }}{{ detail.location }}
            </div>
          </el-form-item>
          <!-- <el-form-item label="详细地址：" class="under-item mb10" >
            <div  class="color333">
              {{detail.location}}
            </div>
          </el-form-item> -->
          <el-form-item
            label="机构类型："
            label-position="left"
            class="mb10"
          >
            <div class="color333">
              {{
                organizations.find((o) => o.key === detail.organization).value
              }}
            </div>
          </el-form-item>
          <el-form-item label="党建模式：" class="mb10">
            <div class="color333">
              {{ customerTypes.find((c) => c.key === detail.type).value }}
            </div>
          </el-form-item>
          <el-form-item label="主控序列号：" class="mb10">
            <div class="color333">
              {{ detail.serial }}
            </div>
          </el-form-item>
          <el-form-item label="是否合同主体：" class="mb10">
            <div class="color333">
              {{ haveOrNot.find((c) => c.key === detail.contract).value }}
            </div>
          </el-form-item>
          <el-form-item
            v-if="detail.contract === 1"
            label="合同编号："
            class="mb10"
          >
            <div class="color333">
              {{ detail.contract_number }}
            </div>
          </el-form-item>
          <el-form-item
            v-if="detail.contract === 1"
            label="合同签订时间："
            class="mb10"
          >
            <div class="color333">
              {{ format(detail.contract_time, "YYYY-MM-DD") }}
            </div>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>
    <!-- 删除弹窗 -->
    <el-dialog
      :visible.sync="visibility"
      width="430px"
      height="100px"
      :show-close="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <div class="dialog-content comfirm-body">
        <img class="comfirm-ico" src="~assets/img/warning.png" />
        <div class="comfirm-txt">
          <div>确定删除该条数据？</div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="visibility = false">取 消</el-button>
        <el-button type="primary" @click="orgDelete">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 切换模式 -->
    <el-dialog
      :visible.sync="modelChange.visible"
      width="635px"
      :close-on-click-modal="false"
      :show-close="false"
      title="切换模式"
    >
      <div class="dialog-body">
        <el-form
          ref="modelForm"
          :model="modelForm"
          label-width="110px"
          label-position="left"
        >
          <el-form-item label="党建模式">
            <el-radio-group v-model="modelForm.type" @change="modelRadioChange">
              <el-radio
                v-for="item in customerTypes"
                :label="item.key"
                :key="item.key"
                >
                {{ item.value }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item v-if="modelForm.type === 0" class="under-item required">
            <el-input
              :disabled="true"
              v-model="modelForm.serial"
              name="editSerial"
              v-validate="'required|serial'"
              placeholder="请输入主控序列号"
            ></el-input>
            <div v-show="errors.has('editSerial')" class="el-form-item__error">
              {{ errors.first("editSerial") }}
            </div>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="closeChangeModel">取 消</el-button>
        <el-button type="primary" @click="saveChangeModel">保 存</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { format } from "silly-datetime";
import * as api from "@/api";
import { limit, middleLimit } from "@/consts/consts";
import {
  organizations,
  customerTypes,
  haveOrNot,
  licenses,
} from "@/consts/codesMap";
import { orgFormKey } from "@/consts/formKey";
import { generateUUID } from "@/utils/tool";

export default {
  data() {
    return {
      btnPermiss: [],
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now() - 8.64e6;
        },
      },
      limit: document.body.clientHeight >= 770 ? limit : middleLimit,
      organizations,
      customerTypes,
      haveOrNot,
      licenses,
      total: 0,
      offset: sessionStorage.getItem("orgOffset") ? +sessionStorage.getItem("orgOffset") : 0,
      tableData: [],
      format,
      search: "",
      licenseState: "",
      model: {
        type: "add",
        visible: false,
      },
      provinceList: [],
      cityList: [],
      districtList: [],
      org_id: "",
      form: { ...orgFormKey },
      detail: {},
      visibility: false,
      organizationData: [],
      detailVisable: false,
      modelChange: {
        visible: false,
      },
      modelForm: {
        type: "",
        serial: "",
      },
      orginType: null,
    };
  },
  computed: {
    isShowModel() {
      return this.form.type === 0 && this.model.type == "add";
    },
  },
  watch: {
    licenseState() {
      this.offset = 0;
      this.orgList();
    },
    "model.visible"(val) {
      this.cityList = [];
      this.districtList = [];
    },
  },
  methods: {
    open(type, row = null) {
      this.$validator.reset();
      this.model.type = type;
      if (row) {
        for (const k in orgFormKey) {
          this.form[k] = row[k];
        }
        this.org_id = row.org_id;
        this.areaList();
      } else {
        this.form.serial = generateUUID()
      }

      this.model.visible = true;
    },

    openDetail(row) {
      this.detail = row;
      this.detailVisable = true;
    },

    closeDetail() {
      this.detail = {};
      this.detailVisable = false;
    },

    jump(path, row) {
      sessionStorage.setItem("orgForm", JSON.stringify(row));
      sessionStorage.setItem("orgOffset", this.offset);
      this.$router.push(`/${path}/${row.org_id}`);
    },

    getChangePage(val) {
      this.offset = val.offset;
      this.orgList();
    },

    searchChange(e) {
      this.search = e;
      this.offset = 0;
      this.orgList();
    },

    areaChange(e, key) {
      this.form[key] = "";
      this[`${key}List`] = [];
      this.$set(this.form, "district", "");
      this.districtList = [];
      this.areaList(e, key);
    },

    radioChange(label) {
      this.form.contract = label;
    },
    close() {
      this.model.visible = false;
      this.form = { ...orgFormKey };
    },

    submit() {
      this.$validator.validateAll().then((valid) => {
        if (valid) {
          this.addOrEdit();
        } else {
          this.$message.warning("有信息未填写正确");
        }
      });
    },

    // 切换模式
    changeType(row) {
      this.$validator.reset();
      this.org_id = row.org_id;
      this.orginType = row.type;
      this.modelForm.type = row.type;
      this.modelForm.serial = row.serial || generateUUID();
      this.modelChange.visible = true;
    },
    closeChangeModel() {
      this.modelChange.visible = false;
    },
    // 切换模式
    modelRadioChange(label) {
      this.modelForm.type = label;
    },

    saveChangeModel() {
      if (this.modelForm.type === 1) {
        this.modelForm.serial = "";
        this.modefiyType();
      } else {
        this.$validator.validate("editSerial").then((valid) => {
          if (valid) {
            this.modefiyType();
          } else {
            this.$message.warning("有信息未填写正确");
          }
        });
      }
    },

    // 机构列表
    async orgList() {
      const { code, data, total } = await api.org(this).orgList({
        offset: this.offset,
        limit: this.limit,
        name: this.search,
        state: this.licenseState,
      });
      if (code === 0) {
        // this.tableData = data
        this.tableData = this.municipality(data);
        this.state = data.license;
        this.total = total;
      }
    },
    //直辖市
    municipality(arr) {
      let municipalityList = "北京市,天津市,上海市,重庆市";
      for (let i = 0; i < arr.length; i++) {
        if (municipalityList.includes(arr[i].province_name)) {
          arr[i].province_name = "";
        }
      }
      return arr;
    },
    // 省、市下拉接口
    async areaList(parent_code = "100000", key = "province") {
      const { code, data } = await api.area(this).areaList({
        parent_code,
      });
      if (code === 0) {
        this[`${key}List`] = data;
        if (this.model.type === "edit") {
          if (key === "province") {
            this.areaList(this.form.province, "city");
          }
          if (key === "city") {
            this.areaList(this.form.city, "district");
          }
        }
      }
    },

    async addOrEdit() {
      let fn = this.model.type === "add" ? "orgAdd" : "orgUpdate";
      if (this.form.type === 1) {
        this.form.serial = "";
      }
      const { code } = await api.org(this)[fn](this.form, this.org_id);
      if (code === 0) {
        this.$message.success("操作成功");
        this.close();
        this.orgList();
      }
    },

    async orgDelete() {
      const { code } = await api.org(this).orgDelete(this.org_id);
      if (code === 0) {
        this.$message.success("操作成功");
        this.org_id = "";
        this.visibility = false;
        if (this.total % this.limit === 1) {
          if (this.offset >= this.limit) {
            this.offset -= this.limit;
          }
        }
        this.orgList();
      }
    },

    async organization() {
      const { code, data } = await api.dropdown(this).organizationList();
      if (code === 0) {
        this.organizationData = data;
      }
    },

    //
    async modefiyType() {
      if (this.modelForm.type === 1) {
        this.modelForm.serial = "";
      }
      const { code } = await api
        .org(this)
        .modefiyType(this.modelForm, this.org_id);
      if (code === 0) {
        this.org_id = "";
        this.modelChange.visible = false;
        if (this.modelForm.type !== this.orginType) {
          this.$message.success("此操作会将终端机初始化，重新选择模式");
        } else {
          this.$message.success("操作成功");
        }

        this.orgList();
      }
    },
  },
  created() {
    this.areaList();
    this.orgList();
    this.organization();
    let permission = JSON.parse(localStorage.getItem("permission"));
    let curMenu = permission.find(item => item.txt === "机构管理")
    this.btnPermiss = curMenu.btns
  },
};
</script>

<style lang="stylus">
.org
  .area-sel
    // width getPx(154)
    width 160px
  .licenseButton
    margin 0 auto
    width getPx(68)
    height getPx(32)
    line-height getPx(32)
    color #fff
  #detail
    .el-form-item__label
      color #666
    .el-form-item__content
      .el-dialog__body
        color #333 !important
  .el-scrollbar .el-select-dropdown__wrap
    max-width 300px !important
  .el-dialog .el-form-item__content:nth-child(1) .el-select .el-input .el-input__inner
    width 340px !important
    overflow hidden
    text-overflow ellipsis
    white-space nowrap
  .selectInput /deep/ .el-input .el-input__inner
    overflow hidden
    text-overflow ellipsis
    white-space nowrap
  .el-dialog .el-form .el-form-item:nth-child(5) .el-form-item__content .el-select .el-input .el-input__inner
    width 340px !important
  .el-dialog .el-form .el-form-item:nth-child(6) .el-form-item__content .el-select .el-input .el-input__inner
    width 340px !important
</style>